package com.zhaoxinms.pdf;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PdfQrCodeGenerator {

    public static void main(String[] args) {
        try {
            // 生成二维码图片
            BufferedImage qrCodeImage = generateQrCode("https://example.com", 200, 200);
            
            // 合成到PDF
            addQrCodeToPdf(
                "input.pdf",    // 原始PDF路径
                "output.pdf",   // 输出PDF路径
                qrCodeImage,    // 二维码图片
                50f,            // X坐标（左下角为原点）
                700f,           // Y坐标
                100f,           // 宽度
                100f            // 高度
            );
            
            System.out.println("PDF生成成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成二维码图片
     * @param content 二维码内容
     * @param width   图片宽度
     * @param height  图片高度
     */
    public static BufferedImage generateQrCode(String content, int width, int height) 
        throws Exception {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1);

        BitMatrix bitMatrix = new MultiFormatWriter().encode(
            content, 
            BarcodeFormat.QR_CODE, 
            width, 
            height, 
            hints
        );

        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }

    /**
     * 将二维码添加到PDF每一页
     * @param inputFile  原始PDF路径
     * @param outputFile 输出PDF路径
     * @param qrImage    二维码图片
     * @param x          X坐标
     * @param y          Y坐标
     * @param width      显示宽度
     * @param height     显示高度
     */
    public static void addQrCodeToPdf(String inputFile, String outputFile, 
                                     BufferedImage qrImage, float x, float y,
                                     float width, float height) 
        throws IOException, DocumentException {
        PdfReader reader = new PdfReader(inputFile);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));

        // 将BufferedImage转换为iText Image
        Image image = Image.getInstance(toByteArray(qrImage));
        image.scaleAbsolute(width, height);

        // 遍历所有页面添加二维码
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            PdfContentByte content = stamper.getOverContent(i);
            image.setAbsolutePosition(x, y);
            content.addImage(image);
        }

        stamper.close();
        reader.close();
    }

    /**
     * 将BufferedImage转换为字节数组
     */
    private static byte[] toByteArray(BufferedImage image) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        javax.imageio.ImageIO.write(image, "PNG", baos);
        return baos.toByteArray();
    }
}